package com.hww.common.util;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;

public abstract class CountDownTimerCu {

    /**
     * 倒计时 时间总数
     * 单位:毫秒
     */
    private final long mMillisInFuture;

    /**
     * 倒计时 间隔时间
     * 单位:毫秒
     */
    private final long mCountdownInterval;

    /**
     * 从调用{@link #start()}方法开始，到需要接受的时间
     * 单位:毫秒
     */
    private long mStopTimeInFuture;

    /**
     * 计数器是否被取消
     */
    private boolean mCancelled = false;

    /**
     * @param millisInFuture    倒计时时间总数 单位:毫秒
     * @param countDownInterval 倒计时间隔时间 单位:毫秒
     */
    public CountDownTimerCu(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
    }

    /**
     * 取消倒计时
     */
    public synchronized final void cancel() {
        mCancelled = true;
        mHandler.removeMessages(MSG);
        onFinish();
    }

    /**
     * 开始倒计时
     * 若上次倒计时为完成，取消上次倒计时，开始本次倒计时
     */
    public synchronized final CountDownTimerCu start() {
        mCancelled = false;
        mHandler.removeMessages(MSG);
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
        /*SystemClock.elapsedRealtime()  从设备开机到现在的时间，单位毫秒，含系统深度睡眠时间*/
        mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
        mHandler.sendMessage(mHandler.obtainMessage(MSG));
        return this;
    }


    /**
     * 按照指点间隔时间触发的回调
     *
     * @param millisUntilFinished 已经完成的时间
     */
    public abstract void onTick(long millisUntilFinished);

    /**
     * 倒计时结束后或取消的时候触发的回调
     */
    public abstract void onFinish();


    private static final int MSG = 1;


    // handles counting down
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            synchronized (CountDownTimerCu.this) {
                if (mCancelled) {
                    return;
                }
                final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
                if (millisLeft <= 0) {
                    onFinish();
                } else {
                    long lastTickStart = SystemClock.elapsedRealtime();
                    onTick(millisLeft);
                    // take into account user's onTick taking time to execute
                    long lastTickDuration = SystemClock.elapsedRealtime() - lastTickStart;
                    long delay;
                    if (millisLeft < mCountdownInterval) {
                        // just delay until done
                        delay = millisLeft - lastTickDuration;
                        // special case: user's onTick took more than interval to
                        // complete, trigger onFinish without delay
                        if (delay < 0) {
                            delay = 0;
                        }
                    } else {
                        delay = mCountdownInterval - lastTickDuration;
                        // special case: user's onTick took more than interval to
                        // complete, skip to next interval
                        while (delay < 0) {
                            delay += mCountdownInterval;
                        }
                    }
                    sendMessageDelayed(obtainMessage(MSG), delay);
                }
            }
        }
    };
}